package com.zwzc.handler;

import com.alibaba.fastjson.JSON;
import com.zwzc.RedisConstants;
import com.zwzc.RedisUtil;
import com.zwzc.enums.ResultEnum;
import com.zwzc.module.common.JsonResult;
import com.zwzc.util.JwtUtils;
import com.zwzc.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ProjectName: zwzc
 * @ClassName: LocalLogoutSuccessHandler
 * @Author: hejialun
 * @Description: 退出登录
 * @Date: 2021/6/21 15:50
 */

@Component
public class LocalLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //清空token
        String token = UserUtil.getTokenByRequest(request);
        //删除token、权限
        redisUtil.del(RedisConstants.USER_INFOS_PREFIX + token);
        redisUtil.del(RedisConstants.USER_ROLE + JwtUtils.getKey(token, "username"));
        response.getWriter().print(JSON.toJSONString(JsonResult.success(ResultEnum.USER_LOGOUT_SUCCESS.getMessage())));
    }

}